package handler

import (
	"car-trade-hub/cache"
	"car-trade-hub/model"
	"car-trade-hub/pkj"
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	cache_key := "login_error" + username
	cacheData, _ := cache.Rdb.Get(cache.Ctx, cache_key).Int()
	if cacheData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	if user.Password != pkj.Str(password) {
		cache.Rdb.Incr(cache.Ctx, cache_key)
		if cacheData == 2 {
			cache.Rdb.Set(cache.Ctx, cache_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁二小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
}
func UserRoleList(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON roles.id = user_roles.rid
		WHERE
		  user_roles.uid = 1
	*/
	var roles model.Role
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id = user_roles.rid").
		Where("user_roles.uid = ?", uid).Find(&roles)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": roles,
	})
}
func UserGetUidRoleList(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON roles.id = user_roles.rid
		WHERE
		  user_roles.uid = 1
	*/
	var roles model.Role
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id = user_roles.rid").
		Where("user_roles.uid = ?", uid).Find(&roles)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "ok",
		"data": roles,
	})

}
func RoleNodeList(c *gin.Context) {
	Rid := c.Query("rid")
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON nodes.id = role_nodes.nid
		WHERE
		  role_nodes.rid = 1
	*/
	var nodes model.Node
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON nodes.id = role_nodes.nid").
		Where(" role_nodes.rid = ?", Rid).Find(&nodes)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "ok",
		"data": nodes,
	})
}
func CarAdd(c *gin.Context) {
	car_code, _ := strconv.Atoi(c.PostForm("car_code"))
	car_name := c.PostForm("car_name")
	car_num, _ := strconv.Atoi(c.PostForm("car_num"))
	data := model.Car{
		//Model:   gorm.Model{},
		CarCode: car_code,
		CarName: car_name,
		CarNum:  car_num,
	}
	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func CarOrderAdd(c *gin.Context) {
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	order_code := c.PostForm("order_code")
	order_num, _ := strconv.Atoi(c.PostForm("order_num"))
	order_price, _ := strconv.Atoi(c.PostForm("order_price"))
	data := model.CarOrder{
		//Model:      gorm.Model{},
		Cid:        cid,
		OrderCode:  order_code,
		OrderNum:   order_num,
		OrderPrice: order_price,
	}
	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func CarOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	cache_key := "page_size_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, cache_key).Result()

	offset := (page - 1) * size
	/*
		SELECT
		 cars.id AS Cid,
		 car_orders.order_code AS OrderCode,
		 car_orders.order_num AS OrderNum,
		 car_orders.order_price AS OrderPrice,
		 cars.car_name AS CarName,
		 cars.car_code AS CarCode,
		 cars.car_num AS CarNum
		FROM
		  cars
		  LEFT JOIN car_orders ON cars.id = car_orders.cid
	*/
	var OrderList []model.CarOrderList
	if cacheData == "" {
		model.DB.Table("cars").Select("cars.id AS Cid",
			"car_orders.order_code AS OrderCode",
			"car_orders.order_num AS OrderNum",
			"car_orders.order_price AS OrderPrice",
			"cars.car_name AS CarName",
			"cars.car_code AS CarCode",
			"cars.car_num AS CarNum").
			Joins("LEFT JOIN car_orders ON cars.id = car_orders.cid").
			Offset(offset).Limit(size).Find(&OrderList)
		jsonData, _ := json.Marshal(&OrderList)
		cache.Rdb.Set(cache.Ctx, cache_key, jsonData, time.Second*120)
	} else {
		json.Unmarshal([]byte(cacheData), &OrderList)
	}

	var total int64
	model.DB.Model(model.CarOrder{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "获取成功",
		"data":  OrderList,
		"total": total,
	})
}
